<?php
namespace App\Models\Traits;
use App\Models\Comment;
use App\Models\Post;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/4 0004
 * Time: 15:23
 */

trait ActiveUserHelper {


    public function getActiveUser() {
        return Cache::remember('user_score',60,function () {
            return $this->calculateActiveUser();
        });
    }

    public function calculateActiveUser() {

        $scores = [];
        $posts = Post::query()->select(DB::raw('user_id,count(*) as post_count'))
            ->where('created_at','>=',Carbon::now()->subDays(7))
            ->groupBy('user_id')->get();
        foreach ($posts as $post) {
            $scores[$post->user_id]['score'] = $post->post_count*3;
        }

        $comments = Comment::query()->select(DB::raw('user_id, count(*) as comment_count'))
            ->where('created_at','>=',Carbon::now()->subDays(7))
            ->groupBy('user_id')
            ->get();

        foreach ($comments as $comment) {
            $comment_score = $comment->comment_count*1;
            if (isset($scores[$comment->user_id])) {
                $scores[$comment->user_id]['score']+=$comment_score;
            } else {
                $scores[$comment->user_id]['score']=$comment_score;
            }
        }

        //dd($scores);

        $data =  array_sort($scores,function ($value,$index) {
            return $value['score'];
        });

        $data = array_reverse($data,true);
        $data = array_slice($data,0,10,true);
        $ids = collect();
        foreach ($data as $user_id=>$user) {
            $user = User::query()->find($user_id);
            $ids->push($user);
        }
        return $ids;
    }
}